﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VideoCutter
{
    public partial class MainForm : Form
    {
        MovieFile currentVideoFile;
        List<MovieFile> videoQueue;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            videoQueue = new List<MovieFile>();
            cbRealTimePreview_CheckedChanged(cbRealTimePreview, null);
            dgvMovieQueue.AutoGenerateColumns = false;
        }

        private void TsTime_ValueChanged(TimeSpan obj)
        {
            SetSnapshot(obj);
        }

        private void SetMovieFileToUI(MovieFile movieFile)
        {
            txtFileName.Text = movieFile.FileName;
            lbLength.Text = movieFile.DurationStr;
            lbPath.Text = movieFile.FilePath;

            tsStart.Time = movieFile.Start;
            tsEnd.Time = movieFile.End;
            tsTime.Time = movieFile.Start;

            tsEnd.setMaxTime(movieFile.Duration);
            tsStart.setMaxTime(movieFile.Duration);
            tsTime.setMaxTime(movieFile.Duration);
        }
        private void SetSnapshot(TimeSpan time)
        {
            if (currentVideoFile != null)
            {
                Image snapshot = Helper.VideoHelper.GetVideoSnapshot(currentVideoFile.FilePath, time);
                if (snapshot != null)
                {
                    pbPreview.Image = snapshot;
                }
            }
        }

        private void cbRealTimePreview_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.Checked)
            {
                tsTime.ValueChanged += TsTime_ValueChanged;
                btnPlay.Enabled = false;
            }
            else
            {
                tsTime.ValueChanged -= TsTime_ValueChanged;
                btnPlay.Enabled = true;
            }
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            SetSnapshot(tsTime.Time);
        }

        private void btnSetAsStart_Click(object sender, EventArgs e)
        {
            tsStart.Time = tsTime.Time;
        }

        private void btnSetAsEnd_Click(object sender, EventArgs e)
        {
            tsEnd.Time = tsTime.Time;
        }
        private void btnSelFile_Click(object sender, EventArgs e)
        {
            ofdSelMovie.Multiselect = false;
            if (ofdSelMovie.ShowDialog() == DialogResult.OK)
            {
                currentVideoFile = MovieFile.getNew(ofdSelMovie.FileName);
                SetMovieFileToUI(currentVideoFile);
                SetSnapshot(AppVars.emptyTimeSpan);
            }
        }

        private void btnAddToQueue_Click(object sender, EventArgs e)
        {
            
            if (currentVideoFile == null)
                return;
            MovieFile videoFile = MovieFile.getNew(lbPath.Text);
            videoFile.Start = tsStart.Time;
            videoFile.End = tsEnd.Time;

            if (videoQueue == null)
                videoQueue = new List<MovieFile>();
            //int movieIndex = videoQueue.FindIndex(a => a.FilePath == currentVideoFile.FilePath);
            //if (movieIndex < 0)
                videoQueue.Add(videoFile);
            //else
            //    videoQueue[movieIndex] = currentVideoFile;
            RefreshDataGridView();
        }

        private void btnClearQueue_Click(object sender, EventArgs e)
        {
            videoQueue = new List<MovieFile>();
            RefreshDataGridView();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (videoQueue == null || videoQueue.Count < 1)
            {
                MessageBox.Show("视频队列是空的,你需要先将视频加入队列中");
                return;
            }

            btnStart.Enabled = false;
            btnClearQueue.Enabled = false;
            dgvMovieQueue.Enabled = false;
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < videoQueue.Count; i++)
            {
                dgvMovieQueue.ClearSelection();
                //跳过已经处理的行
                if (videoQueue[i].status != MovieFileStatus.Waiting)
                    continue;

                dgvMovieQueue.Rows[i].Selected = true;
                videoQueue[i].status = MovieFileStatus.Processing;
                dgvMovieQueue.Rows[i].Cells[1].Value = videoQueue[i].status;
                dgvMovieQueue.FirstDisplayedScrollingRowIndex = i;
                Application.DoEvents();

                Helper.VideoHelper.CutVideo(i,videoQueue[i].FilePath, videoQueue[i].Start, videoQueue[i].End);

                videoQueue[i].status = MovieFileStatus.Finished;
                dgvMovieQueue.Rows[i].Cells[1].Value = videoQueue[i].status;
                Application.DoEvents();

                //sb.AppendLine(Helper.VideoHelper.generateCutVideoCmd(i,videoQueue[i].FilePath, videoQueue[i].Start, videoQueue[i].End));

            }
            //new FrmText(sb.ToString()).ShowDialog();
            dgvMovieQueue.ClearSelection();
            btnStart.Enabled = true;
            btnClearQueue.Enabled = true;
            dgvMovieQueue.Enabled = true;

        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            FrmAbout f = new FrmAbout();
            f.ShowDialog();
        }

        private void dgvMovieQueue_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                switch (e.ColumnIndex)
                {
                    case 5:
                        editVideoInQueue(e.RowIndex);
                        break;
                    case 6:
                        deleteVideoFromQueue(e.RowIndex);
                        break;
                    case 7:
                        setReprocess(e.RowIndex);
                        break;
                }
            }
        }

        private void deleteVideoFromQueue(int index)
        {
            videoQueue.RemoveAt(index);
            RefreshDataGridView();
        }

        private void editVideoInQueue(int index)
        {
            currentVideoFile = videoQueue[index];
            SetMovieFileToUI(currentVideoFile);
            SetSnapshot(AppVars.emptyTimeSpan);
        }
        private void setReprocess(int index)
        {
            videoQueue[index].status = MovieFileStatus.Waiting;
            RefreshDataGridView();
        }

        private void btnSetAsStartAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(String.Format("把所有视频截取的开始时间设置为{0}?", tsTime.Time), "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                videoQueue.ForEach(a => a.Start = tsTime.Time);
                RefreshDataGridView();
            }
        }

        private void btnSetAsEndAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(String.Format("在所有视频结尾的{0}去掉?",currentVideoFile.Duration- tsTime.Time), "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                TimeSpan t = currentVideoFile.Duration - tsTime.Time;
                videoQueue.ForEach(a =>
                {
                    a.End = a.Duration - t;
                });
                RefreshDataGridView();
            }
        }

        private void dgvMovieQueue_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            foreach (DataGridViewRow row in ((DataGridView)sender).Rows)
            {
                switch ((MovieFileStatus)row.Cells[1].Value)
                {
                    case MovieFileStatus.Waiting:
                        row.Cells[1].Style.ForeColor = Color.DodgerBlue;
                        break;
                    case MovieFileStatus.Processing:
                        row.Cells[1].Style.ForeColor = Color.Orange;
                        break;
                    case MovieFileStatus.Finished:
                        row.Cells[1].Style.ForeColor = Color.Green;
                        break;
                }
            }
        }

        private void btnAddFolder_Click(object sender, EventArgs e)
        {
            
            ofdSelMovie.Multiselect = true;
            if (ofdSelMovie.ShowDialog() == DialogResult.OK)
            {
                foreach (var fileName in ofdSelMovie.FileNames)
                {
                    if (!videoQueue.Exists(a => a.FilePath == fileName))
                    {  
                        videoQueue.Add(MovieFile.getNew(fileName));
                    }
                }
            }
            RefreshDataGridView();
        }

        private void RefreshDataGridView()
        {
            dgvMovieQueue.DataSource = null;
            dgvMovieQueue.DataSource = videoQueue;
        }
    }
}
